package com.tm.filter;
import com.alibaba.fastjson.JSONObject;
import com.tm.enums.StatusCodeEnum;
import com.tm.vo.Result;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author huangp
 * @create 2023-04-16 16:36
 */
@WebFilter(urlPatterns = "/*",filterName = "backendFilter")
public class BackendFilter implements Filter {

    public static ThreadLocal<Long> THREADLOCAL = new ThreadLocal<>();

    private static String[] urls = {
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/img/**",
            "/swagger-ui/**",
            "doc.html",
            "/webjars/**",
            "/api/**",



    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //判断这个路径是否需要去拦截
        String requestURI = request.getRequestURI();
        Boolean checkUrl = checkUrl(requestURI);
        if (checkUrl) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //获取session中用户的信息
        Object emoloyee = request.getSession().getAttribute("emoloyee");
        if (emoloyee == null) {
            //TODD 返回错误信息
            String jsonString = JSONObject.toJSONString(Result.error(StatusCodeEnum.NOT_LOGIN));
            response.getWriter().write(jsonString);
            return;
        }

        THREADLOCAL.set((Long)emoloyee);
        filterChain.doFilter(servletRequest, servletResponse);

    }

    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 校验请求路径是否需要拦截
     * @param requestURI
     * @return
     */
    private static Boolean checkUrl(String requestURI) {
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match) {
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }

}
